import {View, StyleSheet, TextInput, Text, Image, ScrollView, Alert, Platform, PermissionsAndroid} from 'react-native';
import React, {Component} from 'react';
import {Flex, Radio, List, InputItem, WhiteSpace, Modal, PickerView, Provider, Button, Toast} from '@ant-design/react-native';
import {connect} from 'react-redux';
import {saveComHouseInfo} from '~/api/owner';
import {getBuildListByCityId} from '~/api/company';
import Albums from '~/pages/home/album/Album';
import {getBankLoanByBankId} from '~/api/bank';
import {init, setLocatingWithReGeocode, Geolocation} from 'react-native-amap-geolocation';
import {getGeoCity, getCityListOfOpen, getPopularCityListOfOpen} from '~/api/public';
import Album from '~/pages/home/album/Album';

const RadioItem = Radio.RadioItem;

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
    };
};

class AddOwnerInformation extends Component {
    static navigationOptions = {
        title: '添加业主',
    };

    constructor(props) {
        super(props);
        this.state = {
            IDCard: '',
            HouseOwner: '',
            HouseNo: '',
            part1Value: 1,
            part2Value: 1,
            checked: false,
            CityID: this.props.system.city_id,
            CityName: this.props.system.city,
            visible: false,
            buildlist: [],
            buildId: 0,
            buildName: '',
            shenfenimage: [],
            index: this.props.navigation.getParam('index'),
            OwnerFileID: [],
            parkingId: this.props.navigation.getParam('id'),
            CompanyBuildingID: this.props.navigation.getParam('CompanyBuildingID'),
        };
        this.getbuildcitylist();

        this.onpresss = () => {
            this.setState({
                checked: !this.state.checked,
            });
        };
        this.onChange = (value) => {
            let item = this.state.buildlist.find((item) => item.value === value[0]);
            this.setState({
                buildName: item.label,
                buildId: value[0],
            });
        };
        this.onClose = () => {
            this.setState({
                visible: false,
            });
        };
        //热门城市
        getPopularCityListOfOpen().then((r) => {
            if (r.code === 0) {
                // this.props.onSave({
                //     popular_city: r.data,
                // });
            } else {
                alert('获取热门的开放城市失败：' + r.msg);
            }
        });
        getCityListOfOpen().then((r) => {
            if (r.code === 0) {
                let city_list = [];
                let temp_list = [];
                let letter = '';
                r.data.forEach((item) => {
                    if (item.FirstLetter != letter) {
                        if (letter != '') {
                            city_list.push({
                                letter: letter,
                                list: temp_list,
                            });
                        }
                        letter = item.FirstLetter;
                        temp_list = [];
                    }
                    temp_list.push(item);
                });
                city_list.push({
                    letter: letter,
                    list: temp_list,
                });
                // this.props.onSave({
                //     city_list,
                // });
            } else {
                alert('获取开放城市列表失败：' + r.msg);
            }
        });
    }

    async initPostion() {
        // android需要手动获取定位权限
        if (Platform.OS === 'android') {
            await PermissionsAndroid.requestMultiple([PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION]);
        }

        // 初始化高德地图SDK
        await init({
            ios: '05e2900e6e7230c91a628709b777b333',
            android: '55322c82dac3b82cb8ddf649e55f5288',
        });

        // 设定iOS获取定位包含逆地理编码
        if (Platform.OS === 'ios') {
            setLocatingWithReGeocode(true);
        }

        this.getLocation();
    }

    getLocation() {
        if (this.props.system.city === '') {
            Geolocation.getCurrentPosition(
                ({location}) => {
                    getGeoCity({city_id: location.adCode}).then((r) => {
                        if (r.code === 0) {
                            let city = location.district || location.city;
                            let city_id = location.adCode;
                            this.setState({
                                CityName: city,
                                CityID: city_id,
                            });
                            // this.props.onSave({
                            //     longitude: location.longitude,
                            //     latitude: location.latitude,
                            //     city,
                            //     city_id,
                            // });
                        } else {
                            Modal.alert('提示', '你所在城市未开放，请手动选择其它开放的城市。', [
                                {
                                    text: '确定',
                                    onPress: () => {
                                        this.onGoCityPage();
                                    },
                                },
                            ]);
                        }
                    });
                },
                (error) => {
                    alert('获取定位失败：' + error.message);
                },
            );
        } else {
            this.setState({
                CityName: this.props.system.city,
                CityID: this.props.system.city_id,
            });
        }
    }

    onGoCityPage = () => {
        this.props.navigation.navigate('City', {
            updateCityName: (CityName, CityID) => {
                this.setState(
                    {
                        CityName,
                        CityID,
                    },
                    () => {
                        this.getbuildcitylist();
                    },
                );
            },
        });
    };
    getbuildcitylist = () => {
        getBuildListByCityId(this.state.CityID).then((r) => {
            if (r.code === 0) {
                let list = [];
                r.data.forEach((item) => {
                    list.push({
                        label: item.BuildingName,
                        value: item.CompanyBuildingID,
                    });
                });
                this.setState({
                    buildlist: list,
                });
            } else {
                Alert.alert('111失败');
            }
        });
    };

    render() {
        var idcard_regx = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
        const onPress = () => {
            if(this.state.HouseOwner === ''){
                Toast.info('请输入姓名', 1);
            } else if(this.state.IDCard === ''){
                Toast.info('请输入身份证号', 1);
            } else if(this.state.HouseNo === ''){
                Toast.info('请输入门牌号', 1);
            } else if(this.state.buildId === 0) {
                Toast.info('请选择小区', 1);
            } else if(!idcard_regx.test(this.state.IDCard)){
                Toast.info('请输入正确得身份证号码', 1);
            } else {
                        saveComHouseInfo({
                        IDCard: this.state.IDCard,
                        OwnerHouseID: 0,
                        CompanyBuildingID: this.state.buildId,
                        HouseOwner: this.state.HouseOwner,
                        HouseNo: this.state.HouseNo,
                        OwnerFileID: this.state.OwnerFileID,
                    }).then((r) => {
                        if (r.code === 0) {
                            Alert.alert('添加成功');
                            this.props.navigation.push('PersonalInformation');
                        } else {
                            Alert.alert('添加失败');
                        }
                    });
            }
        };
        //PersonalInformation
        const setNumber = (text) => {
            this.setState({
                IDCard: text,
            });
        };
        const setName = (text) => {
            this.setState({
                HouseOwner: text,
            });
        };
        const setMen = (number) => {
            this.setState({
                HouseNo: number,
            });
        };
        return (
            <>
                <ScrollView style={styles.srcollview}>
                    <View
                        style={{
                            width: '100%',
                            height: 60,
                            backgroundColor: '#F8F8FC',
                            justifyContent: 'center',
                            flexDirection: 'column',
                            paddingLeft: 16,
                        }}>
                        <Text style={{fontSize: 14, color: '#A3A3A3'}}>个人基础信息</Text>
                    </View>
                    <WhiteSpace size={'xs'} />
                    <View style={styles.userviews}>
                        <Text style={styles.userText}>真实姓名</Text>
                        <View style={styles.nameinputstyle}>
                            <List>
                                <InputItem placeholder="请输入姓名" onChange={setName} />
                            </List>
                        </View>
                    </View>
                    <WhiteSpace size={'xs'} />
                    <View style={styles.view}>
                        <View
                            style={{
                                flexDirection: 'column',
                                justifyContent: 'center',
                                flex: 1,
                            }}>
                            <View style={styles.userviews}>
                                <Text style={styles.userText}>身份证号码</Text>
                                <View style={styles.nameinputstyle}>
                                    <List>
                                        <InputItem type={'number'} maxLength={18} placeholder="请输入身份证号码" onChange={setNumber} />
                                    </List>
                                </View>
                            </View>
                            <WhiteSpace size="xs" />
                            {/* <View style={styles.userviews}>
                                <Text style={styles.userText}>性别</Text>
                                <View style={styles.nameinputstyle}>
                                    <Flex direction={'row'} justify={'around'}>
                                        <Flex onPress={this.onpresss}>
                                            {this.state.checked == true ? (
                                                <Image
                                                    style={{
                                                        width: 17,
                                                        height: 17,
                                                    }}
                                                    source={require('~/assets/info/noselect2x.png')}
                                                />
                                            ) : (
                                                <Image
                                                    style={{
                                                        width: 17,
                                                        height: 17,
                                                    }}
                                                    source={require('~/assets/info/select2x.png')}
                                                />
                                            )}
                                            <Image
                                                style={{
                                                    width: 17,
                                                    height: 17,
                                                }}
                                                source={require('~/assets/info/nv2x.png')}
                                            />
                                            <Text style={{fontSize: 15}}>女</Text>
                                        </Flex>
                                        <Flex onPress={this.onpresss}>
                                            {this.state.checked == false ? (
                                                <Image
                                                    style={{
                                                        width: 17,
                                                        height: 17,
                                                    }}
                                                    source={require('~/assets/info/noselect2x.png')}
                                                />
                                            ) : (
                                                <Image
                                                    style={{
                                                        width: 17,
                                                        height: 17,
                                                    }}
                                                    source={require('~/assets/info/select2x.png')}
                                                />
                                            )}
                                            <Image style={{width: 15, height: 15}} source={require('~/assets/info/nan2x.png')} />
                                            <Text style={{fontSize: 15}}>男</Text>
                                        </Flex>
                                        <Flex />
                                    </Flex>
                                </View>
                            </View> */}
                            <WhiteSpace size="xs" />
                            <Flex
                                justify={'between'}
                                style={{
                                    width: '100%',
                                    padding: 15,
                                }}>
                                <Text
                                    onPress={this.onGoCityPage}
                                    style={{
                                        fontSize: 14,
                                        color: '#333333',
                                    }}>
                                    当前城市为：{this.state.CityName}
                                    <Image
                                        style={{
                                            width: 10,
                                            height: 11,
                                        }}
                                        source={require('~/assets/shouye/dizhi_12x.png')}
                                    />
                                </Text>

                                <Text
                                    style={{}}
                                    onPress={() => {
                                        this.setState({visible: true});
                                        if (this.state.buildId === 0 && this.state.buildlist.length > 0) {
                                            this.setState({
                                                buildId: this.state.buildlist[0].value,
                                                buildName: this.state.buildlist[0].label,
                                            });
                                        }
                                    }}>
                                    {this.state.buildName == '' ? '选择小区' : this.state.buildName}
                                </Text>
                            </Flex>
                            <Modal popup visible={this.state.visible} animationType="slide-up" onClose={this.onClose}>
                                <View
                                    style={{
                                        paddingVertical: 20,
                                        paddingHorizontal: 20,
                                    }}>
                                    <PickerView onChange={this.onChange} value={[this.state.buildId]} data={this.state.buildlist} cols={1} />
                                </View>
                                <Button type="primary" onPress={this.onClose}>
                                    确定
                                </Button>
                            </Modal>
                            <WhiteSpace size={'xs'} />
                            <View style={styles.userviews}>
                                <Text style={styles.userText}>门牌号</Text>
                                <View style={styles.nameinputstyle}>
                                    <List>
                                        <InputItem placeholder="请输入门牌号" onChange={setMen} />
                                    </List>
                                </View>
                            </View>
                            {/*<View*/}
                            {/*    style={{*/}
                            {/*        width: '100%',*/}
                            {/*        height: 60,*/}
                            {/*        backgroundColor: '#F8F8FC',*/}
                            {/*        justifyContent: 'center',*/}
                            {/*        flexDirection: 'column',*/}
                            {/*        paddingLeft: 16,*/}
                            {/*    }}>*/}
                            {/*    <Text style={{fontSize: 14, color: '#A3A3A3'}}>证件信息</Text>*/}
                            {/*</View>*/}
                        </View>
                        {/*<View*/}
                        {/*    style={{*/}
                        {/*        width: '100%',*/}
                        {/*        // height: 300,*/}
                        {/*        backgroundColor: '#FFFFFF',*/}
                        {/*        paddingTop: 18,*/}
                        {/*    }}>*/}
                        {/*    <Text style={{fontSize: 15, paddingLeft: 15.5}}>上传身份证</Text>*/}
                        {/*    <Flex*/}
                        {/*        direction={'column'}*/}
                        {/*        justify={'between'}*/}
                        {/*        style={{*/}
                        {/*            paddingTop: 10,*/}
                        {/*            width: '100%',*/}
                        {/*        }}>*/}
                        {/*        <Flex direction={'column'}>*/}
                        {/*            <Albums*/}
                        {/*                onSelect={(files) => {*/}
                        {/*                    this.onUpload(1, files);*/}
                        {/*                }}*/}
                        {/*            />*/}
                        {/*            <Text style={{fontSize: 12, marginRight: 18}}>请上传身份证正面</Text>*/}
                        {/*        </Flex>*/}
                        {/*        <Flex direction={'column'}>*/}
                        {/*            <Albums*/}
                        {/*                onSelect={(files) => {*/}
                        {/*                    this.onUpload(1, files);*/}
                        {/*                }}*/}
                        {/*            />*/}
                        {/*            <Text*/}
                        {/*                style={{*/}
                        {/*                    fontSize: 12,*/}
                        {/*                    marginRight: 18,*/}
                        {/*                    marginBottom: 10,*/}
                        {/*                }}>*/}
                        {/*                请上传身份证反面*/}
                        {/*            </Text>*/}
                        {/*        </Flex>*/}
                        {/*    </Flex>*/}
                        {/*</View>*/}
                        <WhiteSpace size={'xs'} />
                        {/*<View*/}
                        {/*    style={{*/}
                        {/*        width: '100%',*/}
                        {/*        height: 175.5,*/}
                        {/*        backgroundColor: '#FFFFFF',*/}
                        {/*        paddingTop: 18,*/}
                        {/*    }}>*/}
                        {/*    <Text style={{fontSize: 15, paddingLeft: 15.5}}>上传房产证</Text>*/}
                        {/*    <Flex*/}
                        {/*        direction={'row'}*/}
                        {/*        justify={'between'}*/}
                        {/*        style={{*/}
                        {/*            paddingTop: 10,*/}
                        {/*            paddingLeft: 13.5,*/}
                        {/*            paddingRight: 13.5,*/}
                        {/*        }}>*/}
                        {/*        <Albums*/}
                        {/*            onSelect={(files) => {*/}
                        {/*                this.onUpload(1, files);*/}
                        {/*            }}*/}
                        {/*        />*/}
                        {/*    </Flex>*/}
                        {/*</View>*/}
                        <View
                            style={{
                                flex: 1,
                                justifyContent: 'center',
                                flexDirection: 'row',
                            }}>
                            <View style={styles.viewbutton}>
                                <Button onPress={onPress} type={'warning'} style={styles.button}>
                                    完成
                                </Button>
                            </View>
                        </View>
                    </View>
                </ScrollView>
            </>
        );
    }
}

export default connect(mapGetter)(AddOwnerInformation);

const styles = StyleSheet.create({
    srcollview: {
        flex: 1,
    },
    userview: {
        flex: 1,
        flexDirection: 'row',
    },
    userText: {
        width: 100,
        height: 50,
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 15,
    },
    userviews: {
        flexDirection: 'row',
        backgroundColor: '#FFFFFF',
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    meninputstyle: {
        justifyContent: 'center',
    },
    view: {
        flex: 1,
        flexDirection: 'column',
    },
    nameinputstyle: {
        width: '65%',
        textAlign: 'center',
        flexDirection: 'column',
        justifyContent: 'center',
    },
    titText: {
        fontSize: 20,
    },
    tituserview: {
        height: 50,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    button: {
        fontSize: 15,
    },
    viewbutton: {
        marginTop: '10%',
        width: '70%',
        height: 44,
        marginBottom: 50,
    },
    seleviews: {
        marginTop: 10,
        flexDirection: 'row',
    },
    seleview: {
        width: 80,
        height: 40,
    },
    selebutton: {
        fontSize: 15,
    },
});
